﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Benefit.Models.Sys;
namespace Benefit.Service.Month
{
    public class ServiceAccountMonthAnalysis : Benefit.Interface.Month.IAccountMonthAnalysis
    {
        Benefit.DB.DBManager db = null;
        public ServiceAccountMonthAnalysis(Benefit.DB.DBManager db)
        {
            this.db = db;
        }



        /// <summary>
        /// 删除当月所有记录
        /// </summary>
        /// <param name="tradeHistoryId"></param>
        public void Delete(int month, int year)
        {
            var query = from t in db.AccountMonthAnalysis where t.Month == month && t.Year == year select t;
            foreach (Models.Month.AccountMonthAnalysis c in query)
            {
                db.AccountMonthAnalysis.Remove(c);
            }
            db.SaveChanges();
        }

        /// <summary>
        /// 保存账号月变化情况
        /// </summary>
        /// <param name="tradeHistoryId">插入时间编号</param>
        /// <param name="pdate">插入时间</param>
        public void InitMonthAccountAnalysis(int month, int year)
        {
            var query = db.Accounts.ToList();
            foreach (Models.Sys.Account account in query)
            {
                Models.Month.AccountMonthAnalysis change = new Models.Month.AccountMonthAnalysis();
                change.AccountId = account.Id;
                var _query = from t in db.AccountDayAnalysis where t.TradeHistory.MPdate == month && t.TradeHistory.YPdate == year && t.AccountId == account.Id select t;
                var query2 = from t in db.AccountMonthAnalysis where t.Month == month && t.Year == year && t.AccountId == account.Id select t;
                if (query2.Count() > 0)//有记录更新
                {
                    change = query2.First();
                }
                if (_query.Count() > 0)
                {
                    change.AvgBillBenefit = _query.Sum(a => a.AvgBillBenefit);
                    change.AvgPostionTime = _query.Sum(a => a.AvgPostionTime);
                    change.MaxReturn = _query.Max(a => a.MaxReturn);
                    change.OverStopLoss = _query.Sum(a => a.OverStopLoss);
                    change.PingJinPing = _query.Sum(a => a.PingJinPing);
                    change.RaiseRate = _query.Sum(a => a.RaiseRate);
                    change.RiskCount = _query.Sum(a => a.RiskCount);
                    change.Utilization = _query.Sum(a => a.Utilization);
                    change.WinRate = _query.Sum(a => a.WinRate);
                    change.Yield = _query.Sum(a => a.Yield);

                }
                change.Year = year;
                change.Month = month;
                if (query2.Count() == 0)
                {
                    db.AccountMonthAnalysis.Add(change);
                }
            }
            db.SaveChanges();
        }
    }
}